// 添加选项
function addOption() {
    const container = document.getElementById('optionsContainer');
    const optionCount = container.children.length + 1;
    
    const div = document.createElement('div');
    div.className = 'input-group mb-2';
    div.innerHTML = `
        <input type="text" class="form-control option-input" placeholder="选项${optionCount}" required>
        <button class="btn btn-outline-danger" type="button" onclick="removeOption(this)">
            <i class="fas fa-times"></i>
        </button>
    `;
    
    container.appendChild(div);
}

// 移除选项
function removeOption(button) {
    const container = document.getElementById('optionsContainer');
    if (container.children.length > 2) {
        button.parentElement.remove();
    } else {
        alert('至少需要保留两个选项！');
    }
}

// 复制链接
function copyLink() {
    const linkInput = document.getElementById('pollLink');
    linkInput.select();
    document.execCommand('copy');
    
    // 显示复制成功提示
    const button = event.target;
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="fas fa-check"></i> 已复制';
    setTimeout(() => {
        button.innerHTML = originalText;
    }, 2000);
}

// 创建投票表单提交
document.getElementById('createPollForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const title = document.getElementById('pollTitle').value.trim();
    const options = Array.from(document.querySelectorAll('.option-input'))
        .map(input => input.value.trim())
        .filter(value => value !== '');
    const multipleChoice = document.getElementById('multipleChoice').checked;
    
    if (title === '') {
        alert('请输入投票标题！');
        return;
    }
    
    if (options.length < 2) {
        alert('请至少添加两个选项！');
        return;
    }
    
    try {
        const response = await fetch('/create', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                title: title,
                options: options,
                multiple_choice: multipleChoice
            })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            // 显示结果卡片
            document.getElementById('resultCard').style.display = 'block';
            document.getElementById('pollLink').value = window.location.origin + data.short_url;
            document.getElementById('viewPollBtn').href = data.short_url;
            
            // 生成二维码
            const qrResponse = await fetch(`/api/qrcode/${data.poll_id}`);
            const qrData = await qrResponse.json();
            document.getElementById('qrCode').src = qrData.qr_code;
            
            // 滚动到结果区域
            document.getElementById('resultCard').scrollIntoView({ behavior: 'smooth' });
            
            // 清空表单
            document.getElementById('createPollForm').reset();
            const container = document.getElementById('optionsContainer');
            container.innerHTML = `
                <div class="input-group mb-2">
                    <input type="text" class="form-control option-input" placeholder="选项1" required>
                    <button class="btn btn-outline-danger" type="button" onclick="removeOption(this)">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="input-group mb-2">
                    <input type="text" class="form-control option-input" placeholder="选项2" required>
                    <button class="btn btn-outline-danger" type="button" onclick="removeOption(this)">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            `;
        } else {
            alert('创建投票失败，请重试！');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('创建投票失败，请检查网络连接！');
    }
});

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 为选项输入框添加回车键事件
    document.addEventListener('keypress', function(e) {
        if (e.target.classList.contains('option-input') && e.key === 'Enter') {
            e.preventDefault();
            if (e.target.parentElement.nextElementSibling) {
                e.target.parentElement.nextElementSibling.querySelector('input').focus();
            } else {
                addOption();
            }
        }
    });
});
